<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        /*
            按左键，往左移
            按右键，往右移
        */
        window.onload = function () {
            //创建一个变量表示方向
            //通过修改dir来影响移动的方向
            var dir = 0;
            //速度
            var speed = 10;
            //开启一个定时器，来控制div的移动
            setInterval(function () {
                /*
                   37 左 
                   38 上
                   39 右
                   40 下
               */
                switch (dir) {
                    case 37:
                        box1.style.left = box1.offsetLeft - speed + "px";
                        break;
                    case 39:
                        box1.style.left = box1.offsetLeft + speed + "px";
                        break;
                    case 38:
                        box1.style.top = box1.offsetTop - speed + "px";
                        break;
                    case 40:
                        box1.style.top = box1.offsetTop + speed + "px";
                        break;
                    default:
                        break;
                }
            }, 30);
            //为document绑定一个按下事件
            document.onkeydown = function (event) {
                event = event || window.event;
                if (event.ctrlKey) {
                    speed = 100;
                } else {
                    speed = 10;
                }
                //使dir等于按键值
                dir = event.keyCode;
            };
            document.onkeyup = function () {
                dir = 0;
            }
        };
    </script>
    <style>
        #box1 {
            width: 100px;
            height: 100px;
            background-color: red;
            position: absolute;
        }
    </style>
</head>

<body>
    <div id="box1"></div>
</body>

</html>